package com.bookstore.controller;
import com.bookstore.entity.Category;
import com.bookstore.service.CategoryService;
import com.bookstore.utils.Json;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

@Controller
public class CategoryController {
    @Autowired
    CategoryService categoryService;


    @ResponseBody
    @RequestMapping(value = "get_category",method = RequestMethod.GET)
    public Json getCategroyByPid(@RequestParam("Pid") Long Pid){
        Json json = new Json();
        List<Category> categoryList = categoryService.getCategoryByPid(Pid);
        json.setObj(categoryList);
        return json;
    }

    @RequestMapping(value = "/into_view_source",method = RequestMethod.GET)
    public String categorySearch(@RequestParam("cId") Long cId,HttpServletRequest request){
        Category category = categoryService.getCategoryByCid(cId);
        Category parent_category = categoryService.getCategoryByCid(new Long(category.getParentId()));
        List<Category> categoryList = new ArrayList<Category>();
        if (parent_category != null) {
            categoryList = categoryService.getCategoryByPid(parent_category.getcId());
            request.setAttribute("parent_category",parent_category);
            request.setAttribute("category",category);
        }else {
            request.setAttribute("parent_category",category);
            request.setAttribute("category",null);
            categoryList = categoryService.getCategoryByPid(category.getcId());
        }
        request.setAttribute("categoryList",categoryList);
        return "jsp/view-source";
    }


}
